package com.qo.qsdk.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.qo.qsdk.model.SDKInfoModel;
import com.qo.qsdk.ui.base.AppleAuthView;
import com.qo.qsdk.utils.QSDKHelper;

import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class AppleAuthActivity extends BaseActivity {
    private static final String TAG = AppleAuthActivity.class.getSimpleName();

   private AppleAuthView mAppleAuthView;

   public static QSDKListener mQSDKListener;

    public static void startActivity(Context context, QSDKListener qsdkListener) {
        try {
            if (context != null) {
                AppleAuthActivity.mQSDKListener = qsdkListener;
                Intent intent = new Intent(context, AppleAuthActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                context.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAppleAuthView = new AppleAuthView(this, mQSDKListener);
        mAppleAuthView.show(this, "", getUrl());
    }

    @Override
    public void onBackPressed() {
        if (mQSDKListener != null) mQSDKListener.onAppleAuthClose();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQSDKListener = null;
    }

    private String getUrl() {
        try {
            SDKInfoModel configModel = QSDKHelper.getInstance().getConfigureModel();
            StringBuffer stringBuffer = new StringBuffer("https://appleid.apple.com/auth/authorize?response_type=code&v=1.1.6&response_mode=form_post&scope=email");
            stringBuffer
                    .append("&client_id=").append(QSDKHelper.getInstance().getConfigureModel().getApple().getClientId())
                    .append("&state=").append(sha256(generateNonce(20)))
                    .append("&nonce=").append(sha256(generateNonce(20)))
                    .append("&redirect_uri=").append(configModel.getApple().getRedirectUri())
                    .append("&locale=").append(configModel.getCurrencyLang().getAppleLocale());

            Log.e(TAG, stringBuffer.toString());
            return stringBuffer.toString();
        }catch (Exception e){
            return "";
        }
    }

    private String generateNonce(int length) {
        SecureRandom generator = new SecureRandom();

        CharsetDecoder charsetDecoder = StandardCharsets.US_ASCII.newDecoder();
        charsetDecoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
        charsetDecoder.onMalformedInput(CodingErrorAction.IGNORE);

        byte[] bytes = new byte[length];
        ByteBuffer inBuffer = ByteBuffer.wrap(bytes);
        CharBuffer outBuffer = CharBuffer.allocate(length);
        while (outBuffer.hasRemaining()) {
            generator.nextBytes(bytes);
            inBuffer.rewind();
            charsetDecoder.reset();
            charsetDecoder.decode(inBuffer, outBuffer, false);
        }
        outBuffer.flip();
        return outBuffer.toString();
    }

    private String sha256(String s) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(s.getBytes());
        StringBuilder hash = new StringBuilder();
        for (byte c: digest) {
            hash.append(String.format("%02x", c));
        }
        return hash.toString();
    }


}
